<template>
    <view class="my-container">
        <view class="user-info">
            <view class="user-info-left">
               <image :src="userInfo?.avatar || 'https://puqinzc.oss-cn-beijing.aliyuncs.com/172ce858557a4833abf34e8f1157eab7.png'" mode="aspectFill" class="logo"></image>
               <view class="user-info-left-realName">
                <view class="user-info-left-realName-text" @click="handleUserInfoClick">{{ hasUserToken() ? (userInfo?.name || '用户') : '未登录' }}</view>
                <!-- 是否认证 -->
                <image 
                    :src="(isPaid || isTeenager) ? '../../static/authentication_2.png' : '../../static/authentication_1.png'" 
                    mode="widthFix" 
                    class="authentication_icon"
                    @click="handleAuthenticationClick"
                ></image>
               </view>
            </view>
            <view class="user-info-right" @click="handleSettingClick">
                <image src="../../static/setting.png" mode="widthFix" class="set-icon"></image>
            </view>
        </view>

        <!-- 完善个人信息 -->
        <view class="complete-info" @click="handleCompleteInfoClick" v-if="hasUserToken() && userInfo && !isAuditPassed && !isTeenager">
            <view class="complete-info-left">
                <image src="../../static/edit.png" mode="widthFix" class="complete-info-icon"></image>
                <view class="complete-info-text">请完善个人信息</view>
            </view>
            <view class="complete-info-btn">立即完善</view>
        </view>

        <!-- 会费缴纳 -->
       <view class="complete-info" @click="handlePayClick" v-if="hasUserToken() && userInfo && shouldShowPayment">
            <view class="complete-info-left">
                <image src="../../static/money.png" mode="widthFix" class="complete-info-icon"></image>
                <view class="complete-info-text">请在30日内完成会费缴纳</view>
            </view>
            <view class="complete-info-btn">去缴纳</view>
        </view>
	


        <!-- 我的证书 -->
        <view class="my-certificate" @click="handleCertificateClick" :class="{'is-info-complete': isInfoComplete}" v-if="hasUserToken() && (isAuditPassed || isTeenager)">
            <view class="left">
                <image src="../../static/book.png" mode="widthFix" class="certificate-icon"></image>
                <view class="certificate-text">我的证书</view>
            </view>
            <view class="right">
                <image src="../../static/right.png" mode="widthFix" class="right-icon"></image>
            </view>
        </view>

        <!-- 我的积分 -->
        <view class="my-cell" @click="handleCellClick('积分')">
            <view class="left">
                <image src="../../static/cell_1.png" mode="widthFix" class="cell-icon"></image>
                <view class="cell-text">我的积分</view>
            </view>
            <view class="right">
                <image src="../../static/right.png" mode="widthFix" class="right-icon"></image>
            </view>
        </view>

        <!-- 我的捐赠记录 -->
        <view class="my-cell" @click="handleCellClick('捐赠记录')">
            <view class="left">
                <image src="../../static/cell_2.png" mode="widthFix" class="cell-icon"></image>
                <view class="cell-text">我的捐赠记录</view>
            </view>
            <view class="right">
                <image src="../../static/right.png" mode="widthFix" class="right-icon"></image>
            </view>
        </view>

        <!-- 我的缴费记录 -->
        <view class="my-cell" @click="handleCellClick('缴费记录')">
            <view class="left">
                <image src="../../static/cell_3.png" mode="widthFix" class="cell-icon"></image>
                <view class="cell-text">我的缴费记录</view>
            </view>
            <view class="right">
                <image src="../../static/right.png" mode="widthFix" class="right-icon"></image>
            </view>
        </view>

        <!-- 我的会员等级 -->
        <view class="my-cell" @click="handleCellClick('会员等级')">
            <view class="left">
                <image src="../../static/cell_4.png" mode="widthFix" class="cell-icon"></image>
                <view class="cell-text">我的会员等级</view>
            </view>
            <view class="right">
                <image src="../../static/right.png" mode="widthFix" class="right-icon"></image>
            </view>
        </view>

        <!-- 退出登录 -->
        <view class="logout-section" v-if="userInfo">
            <view class="logout-btn" @click="handleLogout">退出登录</view>
        </view>

        <!-- 未缴费提示弹窗 -->
        <view class="payment-modal" v-if="showPaymentModal" @click="closePaymentModal">
            <view class="modal-mask"></view>
            <view class="modal-content" @click.stop>
                <view class="modal-header">
                    <view class="modal-title">提示</view>
                </view>
                <view class="modal-body">
                    <view class="modal-message">您还未完成缴费，请缴纳会费后查看</view>
                </view>
                <view class="modal-footer">
                    <view class="modal-btn cancel-btn" @click="closePaymentModal">取消</view>
                    <view class="modal-btn confirm-btn" @click="goToPayment">去缴费</view>
                </view>
            </view>
        </view>
        
    </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { isLoggedIn } from '@/utils/user.js'
import { logout } from '@/utils/auth.js'
import { getMemberInfo } from '@/utils/api.js'

const userInfo = ref(null)
const memberInfo = ref(null)
const loading = ref(false)
const showPaymentModal = ref(false)

// 检查是否有user_token（登录状态）
const hasUserToken = () => {
	try {
		const token = uni.getStorageSync('user_token')
		return !!token
	} catch (e) {
		console.error('检查token失败:', e)
		return false
	}
}

// 获取用户信息
const getUserInfoFromStorage = () => {
	try {
		const userInfoData = uni.getStorageSync('user_info')
		
		// 如果有值并且是字符串，转换为JSON对象
		if (userInfoData && typeof userInfoData === 'string') {
			return JSON.parse(userInfoData)
		}
		
		return userInfoData || null
	} catch (e) {
		console.error('获取用户信息失败:', e)
		return null
	}
}

// 计算属性：判断用户信息是否完整（姓名和手机号都有数据）
const isInfoComplete = computed(() => {
	if (!userInfo.value) return false
    console.log(userInfo.value, userInfo.value.realName, userInfo.value.contactPhone)
	return !!(userInfo.value.realName && userInfo.value.contactPhone)
})

// 计算属性：判断是否应该显示会费缴纳
const shouldShowPayment = computed(() => {
	if (!memberInfo.value) return false
	// 需要满足两个条件：auditStatus == 1（审核通过）且 renew == 1（需要续费）
	return memberInfo.value.auditStatus == 1 && memberInfo.value.renew == 1
})

// 计算属性：判断是否已缴费
const isPaid = computed(() => {
	if (!memberInfo.value) return false
	// 如果renew为0，表示不需要续费，即已缴费
	return memberInfo.value.renew == 0
})

// 计算属性：判断审核是否通过
const isAuditPassed = computed(() => {
	if (!memberInfo.value) return false
	return memberInfo.value.auditStatus == 1
})

// 计算属性：判断是否为青少年
const isTeenager = computed(() => {
	if (!memberInfo.value) return false
	return memberInfo.value.isTeenager == 1
})

// 获取会员信息
const fetchMemberInfo = async () => {
	if (!userInfo.value) return
    // if(userInfo.value.flag2) return
	
	try {
		loading.value = true
		const result = await getMemberInfo()
		
		if (result.code === 0 && result.data) {
			memberInfo.value = result.data
			console.log('会员信息:', memberInfo.value)
			
			// 如果会员通过审核（auditStatus == 1），将memberInfo的姓名和手机号赋值给userInfo
			// if (memberInfo.value.auditStatus == 1 && memberInfo.value.realName && memberInfo.value.contactPhone) {
			// 	// 更新userInfo的姓名和手机号
			// 	userInfo.value.realName = memberInfo.value.realName
			// 	userInfo.value.contactPhone = memberInfo.value.contactPhone
			// }
            if(memberInfo.value.realName && userInfo.value.name == '') userInfo.value.name = memberInfo.value.realName
            if(memberInfo.value.contactPhone) userInfo.value.phone = memberInfo.value.contactPhone
            userInfo.value.flag2 = true;
            uni.setStorageSync('user_info', userInfo.value)
		} else {
			console.error('获取会员信息失败:', result.message)
		}
	} catch (error) {
		console.error('获取会员信息失败:', error)
	} finally {
		loading.value = false
	}
}

// 检查登录状态并跳转
const checkLoginAndRedirect = () => {
	if (!isLoggedIn()) {
		uni.navigateTo({
			url: '/pages/login/index'
		})
		return false
	}
	return true
}

// 关闭缴费提示弹窗
const closePaymentModal = () => {
	showPaymentModal.value = false
}

// 跳转到缴费页面
const goToPayment = () => {
	closePaymentModal()
	uni.navigateTo({
		url: '/pages/my/pay'
	})
}

onMounted(() => {
	// 获取用户信息
	userInfo.value = getUserInfoFromStorage()
	// 如果有用户信息，获取会员信息
	if (userInfo.value) {
		fetchMemberInfo()
	}
})

onShow(() => {
	// 每次显示页面时获取用户信息
	userInfo.value = getUserInfoFromStorage()
	// 如果有用户信息，获取会员信息
	if (userInfo.value) {
		fetchMemberInfo()
	}
})

// 处理用户信息点击
const handleUserInfoClick = () => {
	if (!hasUserToken()) {
		// 未登录状态，跳转到登录页
		uni.navigateTo({
			url: '/pages/login/index'
		})
		return
	}
	// 已登录状态，可以添加其他逻辑，比如跳转到个人信息页
}

// 处理设置点击
const handleSettingClick = () => {
	if (!checkLoginAndRedirect()) return
	
	goToCompleteInfo()
}

// 处理完善信息点击
const handleCompleteInfoClick = () => {
	if (!checkLoginAndRedirect()) return
	
	goToCompleteInfo()
}

// 处理会费缴纳点击
const handlePayClick = () => {
	if (!checkLoginAndRedirect()) return
	
	uni.navigateTo({
		url: '/pages/my/pay'
	})
}

// 处理认证标识点击
const handleAuthenticationClick = () => {
	if (!checkLoginAndRedirect()) return
	
	// 如果是青少年，直接跳转到证书页面
	if (isTeenager.value) {
		goToCertificate()
		return
	}
	
	// 检查是否已通过审核
	if (!isAuditPassed.value) {
		uni.showToast({
			title: '您还未通过入会审核',
			icon: 'none'
		})
		return
	}
	
	// 检查是否已缴费
	if (!isPaid.value) {
		// 未缴费，显示提示弹窗
		showPaymentModal.value = true
		return
	}
	
	// 已审核通过且已缴费，正常跳转到证书页面
	goToCertificate()
}

// 处理证书点击
const handleCertificateClick = () => {
	if (!checkLoginAndRedirect()) return
	
	// 如果是青少年，直接跳转到证书页面
	if (isTeenager.value) {
		goToCertificate()
		return
	}
	
	// 检查是否已通过审核
	if (!isAuditPassed.value) {
		uni.showToast({
			title: '您还未通过入会审核',
			icon: 'none'
		})
		return
	}
	
	// 检查是否已缴费
	if (!isPaid.value) {
		// 未缴费，显示提示弹窗
		showPaymentModal.value = true
		return
	}
	
	// 已审核通过且已缴费，正常跳转到证书页面
	goToCertificate()
}

const goToCompleteInfo = () => {
    uni.navigateTo({
        url: '/pages/my/completeInfo'
    })
}

const goToCertificate = () => {
    uni.navigateTo({
        url: '/pages/my/certificate'
    })
}

// 处理新功能模块点击
const handleCellClick = (type) => {
    if (!checkLoginAndRedirect()) return
    
    switch (type) {
        case '缴费记录':
            uni.navigateTo({
                url: '/pages/my/payRecord'
            })
            break
        default:
            uni.showToast({
                title: '暂未开放',
                icon: 'none',
                duration: 2000
            })
    }
}

const handleLogout = () => {
    uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
            if (res.confirm) {
                logout()
                // 退出后刷新用户信息
                userInfo.value = null
                memberInfo.value = null
            }
        }
    })
}
</script>

<style lang="scss" scoped>
.my-container{
    min-height: 100vh;
    background: url('https://puqinzc.oss-cn-beijing.aliyuncs.com/57d9daf3195b8a731bad1e14b337b79a.png'), linear-gradient(180deg, #FFE9DA 8%, #F8F9FB 34%);
    background-size: 100% auto;
    background-position: top center;
    background-repeat: no-repeat;
    padding-bottom: 40rpx;

    .user-info{
        padding: 0 24rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 196rpx;

        .user-info-left{
            display: flex;
            align-items: center;

            .logo{
                width: 128rpx !important;
                height: 128rpx !important;
                border-radius: 50%;
                flex-shrink: 0;
            }

            .user-info-left-realName{
                font-size: 32rpx;
                color: #000000;
                line-height: 48rpx;
                margin-left: 16rpx;
                font-weight: bold;
                display: flex;
                flex-direction: column;
                justify-content: center;

                .user-info-left-realName-text{
                    cursor: pointer;
                    transition: color 0.3s ease;
                }

                .authentication_icon{
                    width: 138rpx;
                    height: 44rpx;
                    margin-top: 2rpx;
                    cursor: pointer;
                }
            }
        }

        .user-info-right{
            image{
                width: 48rpx;
                height: 48rpx;
                margin-top: 18rpx;
            }
        }
    }     
    
    .complete-info{
        height: 104rpx;
        margin: 48rpx 24rpx 0;
        padding: 0 24rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: url('../../static/info-bg.png') no-repeat;
		background-size: 100% 100%;

        .complete-info-left{
            display: flex;
            align-items: center;

            .complete-info-icon{
                width: 48rpx;
                height: 48rpx;
            }

            .complete-info-text{
                padding-left: 8rpx;
                color:#FFF;
                font-size: 28rpx;
                line-height: 44rpx;
            }
        }

        .complete-info-btn{
            width: 160rpx;
            height: 60rpx;
            line-height: 60rpx;
            text-align: center;
            background: #fff;
            border-radius: 38rpx;
            color: #FC8759;
        }
    }

    .my-certificate{
        height: 128rpx;
        margin: 20rpx 24rpx 0;
        padding: 0 24rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: #fff;
        border-radius: 16rpx;
        border: 2rpx solid #E7E8EB;

        &.is-info-complete{
            margin-top: 48rpx;
        }

        .left{
            display: flex;
            align-items: center;
            
            .certificate-icon{
                width: 48rpx;
                height: 48rpx;
            }

            .certificate-text{
                font-size: 28rpx;
                color: #000000; 
                margin-left: 16rpx;
            }
        }

        .right{
            image{
                width: 24rpx;
                height: 24rpx;
            }

            .right-icon {
                width: 24rpx;
                height: 24rpx;
                flex-shrink: 0;
            }
        }
    }

    .my-cell{
        height: 128rpx;
        margin: 20rpx 24rpx 0;
        padding: 0 24rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: #fff;
        border-radius: 16rpx;
        border: 2rpx solid #E7E8EB;

        .left{
            display: flex;
            align-items: center;
            
            .cell-icon{
                width: 48rpx;
                height: 48rpx;
            }

            .cell-text{
                font-size: 28rpx;
                color: #000000; 
                margin-left: 16rpx;
            }
        }

        .right{
            image{
                width: 24rpx;
                height: 24rpx;
            }

            .right-icon {
                width: 24rpx;
                height: 24rpx;
                flex-shrink: 0;
            }
        }
    }

    .logout-section {
        margin: 60rpx 24rpx 0;
        
        .logout-btn {
            height: 88rpx;
            line-height: 88rpx;
            text-align: center;
            background: #fff;
            border-radius: 16rpx;
            border: 2rpx solid #E7E8EB;
            color: #FF4757;
            font-size: 28rpx;
        }
    }

    // 缴费提示弹窗样式
    .payment-modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 999;
        display: flex;
        align-items: center;
        justify-content: center;

        .modal-mask {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            position: relative;
            width: 600rpx;
            background: #FFFFFF;
            border-radius: 16rpx;
            z-index: 1000;
            overflow: hidden;

            .modal-header {
                padding: 32rpx 24rpx 0;
                text-align: center;

                .modal-title {
                    font-size: 32rpx;
                    font-weight: 600;
                    color: #000;
                    line-height: 44rpx;
                }
            }

            .modal-body {
                padding: 32rpx 24rpx;

                .modal-message {
                    font-size: 28rpx;
                    color: #666;
                    line-height: 40rpx;
                    text-align: center;
                }
            }

            .modal-footer {
                display: flex;
                border-top: 2rpx solid #f0f0f0;

                .modal-btn {
                    flex: 1;
                    height: 88rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 28rpx;
                    transition: all 0.3s ease;

                    &.cancel-btn {
                        color: #666;
                        border-right: 2rpx solid #f0f0f0;
                    }

                    &.confirm-btn {
                        color: #F9623E;
                        font-weight: 600;
                    }

                    &:active {
                        background: #f5f5f5;
                    }
                }
            }
        }
    }
}
</style>